﻿using BaseAuthRole.AspNetCore;
using BaseAuthRole.AspNetCore.Client;
using BaseAuthRole.Domain.Input;
using BaseAuthRole.IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Environment;
using RS.Tool.Init;
using System.Reflection;
using System.Web;

namespace BaseAuthRole.Web.Filters
{
    public class ApiAuthCheckFilter: ActionFilterAttribute
    {
        //action执行后
        public override void OnActionExecuted(ActionExecutedContext context)
        {
          
        }
        //action执行前
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            var arguments = context.ActionArguments;
           
            var method=context.HttpContext.Request.Method;


            var userService = ServiceLocator.Instance.GetService<IUserService>();

            var referer = "";

            var iflogined = false; ;

            if (context.HttpContext.Request.Headers.ContainsKey("Referer"))
            {

                referer = context.HttpContext.Request.Headers["Referer"];

            }

            //TODO 

            if (arguments.Count != 0)
            {
                var model_str = JsonConvert.SerializeObject(arguments.First().Value);
                var model = JsonConvert.DeserializeObject<BaseUserInputModel>(model_str);
                //var model = (BaseUserInputModel)arguments.First().Value;


                if (context.HttpContext.Request.Headers.ContainsKey("AuthToken"))
                {
                    var authToken = context.HttpContext.Request.Headers["AuthToken"];
                    if (!string.IsNullOrEmpty(authToken))
                    {
                        model.AuthToken = authToken;

                        var paraObject = arguments.First().Value;
                        Type t = paraObject.GetType();
                        PropertyInfo pi1 = t.GetProperty("AuthToken");
                        //给AuthToken属性赋值 
                        pi1.SetValue(paraObject, authToken.ToString(), null);
                    }
                }

                var temp_r = userService.GetUserInfo(new GetUserInfoInput { 
                 AuthToken= model.AuthToken
                });

                if (temp_r.IsError)
                {
                    if (temp_r.Value == RS.BaseModel.Enum.EnumBaseResult.NoLogin)
                    {
                        var r = new CommonResult();

                        r.Value = RS.BaseModel.Enum.EnumBaseResult.NoLogin;
                        r.Message = "未登录";

                        r.Result = BuildAuthUrl(referer);

                        context.Result = new ContentResult { Content = JsonConvert.SerializeObject(r), ContentType = "application/json" };

                    }
                    else
                    {

                        context.Result = new ContentResult { Content = JsonConvert.SerializeObject(temp_r), ContentType = "application/json" };

                    }
                }
                else
                {
                    iflogined = true;
                    //补充Uid

                    var paraObject = arguments.First().Value;

                    Type t = paraObject.GetType();

                    PropertyInfo pi1 = t.GetProperty("Uid");
                    //给MyName属性赋值 
                    pi1.SetValue(paraObject, temp_r.Result.Uid, null);

                }

            }
            else
            {

                var r = new CommonResult();
                r.Value = RS.BaseModel.Enum.EnumBaseResult.NoLogin;
                r.Message = "未登录";
                r.Result = BuildAuthUrl(referer);
                context.Result = new ContentResult { Content = JsonConvert.SerializeObject(r), ContentType = "application/json" };
            }





        }


        /// <summary>
        /// 没有回调地址的，登录后调回Home页
        /// </summary>
        /// <param name="redirectUri"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        public string BuildAuthUrl(string redirectUri, string scope = "auth_base")
        {

            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = ConfigurationHelper.GetAppSettings("HomeUrl");
            }

            var RedirectUri = ConfigurationHelper.GetAppSettings("AuthCodeUrl") + $"?return_url={HttpUtility.UrlEncode(redirectUri)}";

            var url = ConfigurationHelper.GetAppSettings("AuthDomain") + $"/OAuth2/PublicAppAuthorize?AppId={ConfigurationHelper.GetAppSettings("AppId")}&Scope={scope}&RedirectUri={HttpUtility.UrlEncode(RedirectUri)}";

            return url;

        }
    }
}
